#include "pilink_udp_linux.h"
#include "pilink_core.h"

int pilink_udp_socket_init(struct pilink_udp_socket_s *net, int local_port)
{	
	if(net->socket_fd > -1){
		close(net->socket_fd);
	}

	bzero(&net->local_addr, sizeof(net->local_addr));

	net->local_port = local_port;

	net->local_addr.sin_family      = AF_INET;
	net->local_addr.sin_port        = htons(net->local_port);
	net->local_addr.sin_addr.s_addr = htonl(INADDR_ANY) ;
	net->local_addr_len             = sizeof(net->local_addr);

	if((net->socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		return -1;
	}

	int ret = bind(net->socket_fd, (struct sockaddr *)&(net->local_addr), net->local_addr_len);
	if(ret < 0){
		return ret;
	}

	int	flag = fcntl(net->socket_fd , F_GETFL , 0);
	fcntl(net->socket_fd,F_SETFL,flag | O_NONBLOCK);

	return 0;
}

void pilink_udp_socket_set_dest_addr(struct pilink_udp_socket_s *net, char *ip, int port )
{
	bzero(&net->dest_addr, sizeof(net->dest_addr));
	net->dest_addr.sin_family = AF_INET;
	net->dest_addr.sin_port = htons(port);

	if(ip == NULL){
		printf("error: no destination ip address \r\n");
	}else{
		net->dest_addr.sin_addr.s_addr = inet_addr(ip);
	}
	net->dest_addr_len = sizeof(net->dest_addr);
}

int pilink_udp_socket_read(struct pilink_udp_socket_s *net, void *buffer, int size)
{
    int len = recvfrom(net->socket_fd, buffer, size, 0,(struct sockaddr *)&net->recved_addr, (socklen_t*)&net->recved_addr_len); 
	return len;
}

int pilink_udp_socket_write(struct pilink_udp_socket_s *net, const void *buffer, int size)
{
	int len = sendto(net->socket_fd, buffer, size, 0,(struct sockaddr *)&net->dest_addr, net->dest_addr_len);
	return len;
}


int pilink_udp_socket_deinit(struct pilink_udp_socket_s *net)
{
	if(net->socket_fd > -1){
		close(net->socket_fd);
	}
}

